package com.jadesoft.stock;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.EmailException;

import com.jadesoft.common.service.PaginationService;
import com.jadesoft.stock.entity.StockPrice;
import com.jadesoft.stock.entity.User;

public class UserBSImpl implements UserBS {
	private PaginationService persistence = new PaginationService();
	private MailBS mailBS = new MailBSImpl();
	/**
	 * 保存或更新
	 */
	public User save(User user) {
		if(user.getId() == null){
			return (User) persistence.saveObj(user);
		}else{
			this.persistence.updateObj(user);
			return user;
		}
	}

	/**
	 * 根据用户名或者用户名+密码获取用户
	 */
	public User find(User user) {
		String hql = " from User where email = ? ";
		List args = new ArrayList();
		args.add(user.getEmail());
		if (StringUtils.isNotBlank(user.getPassword())) {
			hql += " and password = ?";
			args.add(user.getPassword());
		}
		List result = persistence.query(hql,args.toArray());
		return result.size() > 0 ? (User) result.get(0) : null;
	}
	
	/**
	 * 用户注册
	 * @param user
	 * @return
	 * @throws EmailException 
	 * @throws MalformedURLException 
	 */
	public User registerTA(User user) throws EmailException{
		this.save(user);
		mailBS.sendAuthMail(user);
		return user;
	}
	
	/**
	 * 激活用户
	 * @param user
	 * @return
	 * @throws EmailException 
	 * @throws MalformedURLException 
	 */
	public User activeTA(User user) throws EmailException{
		this.save(user);
		mailBS.sendActiveMail(user);
		return user;
	}
	
	public static void main(String[] args) {
//		UserBSImpl i = new UserBSImpl();
//		User u =  new User();
//		u.setEmail("b");
//		u.setPassword("aa");
//		u.setName("杨");
//		u.setState(0);
//		i.save(u);
		
		StockPrice p = new StockPrice();
		p.setSymbol("222");
		p.setName("cc");
		new PaginationService().saveObj(p);
	}

}
